import React, { useState, useRef, useEffect } from 'react';
import { Input, Button, Spin, message, Typography } from 'antd';
import { SendOutlined } from '@ant-design/icons';
import { chatWithAI } from '@/services/depositAiService';
import { getUser } from '@/utils/auth';
import './index.less';

const { TextArea } = Input;
const { Title, Paragraph } = Typography;

/**
 * 消息类型
 */
interface Message {
  /**
   * 消息内容
   */
  content: string;
  /**
   * 消息类型：user-用户消息，ai-AI消息
   */
  type: 'user' | 'ai';
  /**
   * 消息时间
   */
  timestamp: string;
}

/**
 * DeepSeek AI助手页面
 */
const DepositAI: React.FC = () => {
  // 存储对话历史
  const [messages, setMessages] = useState<Message[]>([]);
  // 当前输入的消息
  const [inputMessage, setInputMessage] = useState('');
  // 对话ID，用于维持会话上下文
  const [conversationId, setConversationId] = useState<string | undefined>(undefined);
  // 是否正在等待AI回复
  const [loading, setLoading] = useState(false);
  // 消息容器的引用，用于自动滚动
  const messagesEndRef = useRef<HTMLDivElement>(null);

  /**
   * 每当消息列表更新时，滚动到最新消息
   */
  useEffect(() => {
    messagesEndRef.current?.scrollIntoView({ behavior: 'smooth' });
  }, [messages]);

  /**
   * 发送消息到AI助手
   */
  const sendMessage = async () => {
    // 检查消息是否为空
    if (!inputMessage.trim()) {
      message.warning('请输入您的问题');
      return;
    }

    // 获取当前用户信息
    const currentUser = getUser();
    const username = currentUser?.englishName || '未知用户';

    // 添加用户消息到历史
    const userMessage: Message = {
      content: inputMessage,
      type: 'user',
      timestamp: new Date().toISOString(),
    };
    setMessages((prev) => [...prev, userMessage]);
    
    // 清空输入框
    setInputMessage('');
    
    // 设置加载状态
    setLoading(true);

    try {
      // 调用API与AI对话
      const response = await chatWithAI({
        message: userMessage.content,
        conversationId,
        username, // 添加用户名
      });

      // 保存对话ID
      setConversationId(response.conversationId);

      // 添加AI回复到历史
      const aiMessage: Message = {
        content: response.response,
        type: 'ai',
        timestamp: response.timestamp,
      };
      setMessages((prev) => [...prev, aiMessage]);
    } catch (error) {
      // 处理错误
      console.error('对话失败:', error);
      message.error('与AI助手对话失败，请稍后再试');
      
      // 添加错误消息
      const errorMessage: Message = {
        content: '很抱歉，AI助手暂时无法回答您的问题，请稍后再试。',
        type: 'ai',
        timestamp: new Date().toISOString(),
      };
      setMessages((prev) => [...prev, errorMessage]);
    } finally {
      // 结束加载状态
      setLoading(false);
    }
  };

  /**
   * 处理输入框按键事件
   */
  const handleKeyDown = (e: React.KeyboardEvent<HTMLTextAreaElement>) => {
    // 按下Ctrl+Enter发送消息
    if (e.key === 'Enter' && e.ctrlKey) {
      e.preventDefault();
      sendMessage();
    }
  };

  return (
    <div className="deposit-ai-container">
      {/* 页面标题 */}
      <div className="deposit-ai-header">
        <Title level={3}>欢迎使用存款AI助手</Title>
      </div>
      
      {/* 对话区域 */}
      <div className="deposit-ai-chat-container">
        {messages.length === 0 ? (
          <div className="deposit-ai-empty-chat">
            <Paragraph>您可以向AI助手询问任何问题，获取帮助和建议</Paragraph>
          </div>
        ) : (
          messages.map((msg, index) => (
            <div
              key={index}
              className={`deposit-ai-message ${msg.type === 'user' ? 'deposit-ai-user-message' : 'deposit-ai-ai-message'}`}
            >
              <div className="deposit-ai-message-content">
                <Paragraph>{msg.content}</Paragraph>
              </div>
            </div>
          ))
        )}
        
        {/* 加载状态 */}
        {loading && (
          <div className="deposit-ai-loading-container">
            <Spin size="small" />
            <span className="deposit-ai-loading-text">AI正在思考...</span>
          </div>
        )}
        
        {/* 用于自动滚动的空div */}
        <div ref={messagesEndRef} />
      </div>
      
      {/* 输入区域 */}
      <div className="deposit-ai-input-container">
        <TextArea
          value={inputMessage}
          onChange={(e) => setInputMessage(e.target.value)}
          onKeyDown={handleKeyDown}
          placeholder="请输入您的问题..."
          autoSize={{ minRows: 1, maxRows: 4 }}
          disabled={loading}
        />
        <Button
          type="primary"
          icon={<SendOutlined />}
          onClick={sendMessage}
          loading={loading}
          disabled={!inputMessage.trim()}
        >
          发送
        </Button>
      </div>
    </div>
  );
};

export default DepositAI; 